<template>
  <div>
    <Card>
      <Form ref="formInline" :model="searchForm.item" :rules="searchForm.rules" inline>
        <FormItem prop="user">
          <Input type="text" v-model="searchForm.item.user" placeholder="Username">
          <Icon type="ios-person-outline" slot="prepend"></Icon>
          </Input>
        </FormItem>
        <FormItem prop="password">
          <Input type="password" v-model="searchForm.item.password" placeholder="Password">
          <Icon type="ios-lock-outline" slot="prepend"></Icon>
          </Input>
        </FormItem>
        <FormItem>
          <Button type="primary" @click="handleSubmit('formInline')">查询</Button>
          <Button type="primary" @click="handleSubmit('formInline')">重置</Button>
        </FormItem>
      </Form>

      <Row style="margin-bottom: 10px;">
        <Col span="12">
        <Button icon="ios-download-outline" type="primary">Download</Button>

        </Col>
        <Col span="12">
        <Button icon="ios-download-outline" type="primary">Download</Button>

        </Col>
      </Row>

      <Alert show-icon>当前表格已选择 <span style="font-weight: bold; color: blue;">{{selection.length}}</span> 项
        <a @click="$refs.table.selectAll(false)">清空</a>
      </Alert>

      <Table ref="table" :data="tableData" :loading="loading" :columns="columns"
             @on-sort-change="onSortChange"
             @on-delete="handleDelete"
             @on-selection-change="onSelectionChange"
      >
        <template slot="action" slot-scope="props">
          <Button :disabled="props.index>5" type="primary" size="small">通过</Button>
          <Divider type="vertical" />
          <Button :disabled="props.index>5" type="primary" size="small" @click="onShowEditForm(props)">EDIT</Button>
          <Divider type="vertical" />
          <Poptip confirm title="Delete this item?" transfer @on-ok="onDelete(props)">
            <Button type="warning" size="small" >删除</Button>
          </Poptip>
        </template>
        <template slot="switch" slot-scope="props">
          <i-switch v-model="props.row.activated" size="large" @on-change="onSwitchChange(props)">
            <span slot="open">true</span>
            <span slot="close">false</span>
          </i-switch>
        </template>
      </Table>
      <div style="margin: 10px;overflow: hidden">
        <div style="float: right;">
          <Page show-elevator show-sizer show-total :total="page.total" :current="page.current" :page-size="page.pageSize" @on-change="onPageChange" @on-page-size-change="onPageSizeChange"></Page>
        </div>
      </div>
    </Card>

    <Modal
      v-model="editForm.visible"
      :title="editForm.title"
      :loading="editForm.loading"
      @on-ok="onOk"
      @on-cancel="onCancel">
      <Form ref="form" :model="editForm.item" :rules="editForm.rules" :label-width="80">
        <FormItem label="Name" prop="name">
          <Input v-model="editForm.item.name" placeholder="Enter name"></Input>
        </FormItem>
        <FormItem label="Login Name" prop="loginName">
          <Input v-model="editForm.item.loginName" placeholder="Enter login name, it is unique"></Input>
        </FormItem>
        <FormItem label="Roles" prop="roles">
          <CheckboxGroup v-model="editForm.item.roles">
            <Checkbox :label="role" v-for="(role,index) in roles" :key="index"></Checkbox>
          </CheckboxGroup>
        </FormItem>
        <FormItem label="Activated">
          <i-switch v-model="editForm.item.activated" size="large">
            <span slot="open">true</span>
            <span slot="close">false</span>
          </i-switch>
        </FormItem>
        <!--<FormItem>
          <Button type="primary">Submit</Button>
          <Button style="margin-left: 8px">Cancel</Button>
        </FormItem>-->
      </Form>
    </Modal>
  </div>
</template>

<script>
import userApi from '@/api/user'
export default {
  name: 'user_list',
  components: {
  },
  data () {
    return {
      loading: false,
      roles: ['normal','admin','super_admin'],
      searchForm: {
        item: {
          user: '',
          password: ''
        },
        rules: {
          user: [
            { required: true, message: 'Please fill in the user name', trigger: 'blur' }
          ],
          password: [
            { required: true, message: 'Please fill in the password.', trigger: 'blur' },
            { type: 'string', min: 6, message: 'The password length cannot be less than 6 bits', trigger: 'blur' }
          ]
        }
      },
      editForm: {
        visible: false,
        loading: true,
        title: 'User',
        item: {
          name: '',
          enName: '',
          loginName: '',
          roles: ['normal'],
          activated: true
        },
        rules: {
          name: [
            { required: true, message: 'Name cannot be empty', trigger: 'blur' }
          ],
          loginName: [
            { required: true, message: 'Login name cannot be empty', trigger: 'blur' }
          ],
          roles: [
            { required: true, type: 'array', min: 1, message: 'Choose at least one role', trigger: 'change' }
          ]
        }
      },
      selection: [],
      page: {
        pageSize: 10,
        total: 0,
        current: 1,
        sort: {
        }
      },
      tableData: [],
      columns: [
        {
          type: 'selection',
          width: 60,
          align: 'center'
        },
        {title: 'Name', key: 'name', sortable: true},
        {title: 'Roles', key: 'roles'},
        {title: 'Login Name', key: 'loginName', sortable: true},
        {
          title: 'Activated',
          key: 'activated',
          render: (h, params) => {
            return h(
              'div',
              this.$refs.table.$scopedSlots.switch(params)
            )
          }
        },
        {
          title: 'Action',
          key: 'action',
          align: 'center',
          render: (h, params) => {
            return h(
              'div',
              this.$refs.table.$scopedSlots.action(params)
            )
          }
        }
      ]
    }
  },
  methods: {
    handleDelete (params) {
      console.log(params)
    },
    onSwitchChange ({row, column, index}) {
      let item = { id: row.id, activated: row.activated}
      userApi.save(item).then(res => {
        this.$Message.success('Success!');
      })
    },
    onShowEditForm ({row, column, index}) {
      this.editForm.visible = true
      this.editForm.item = Object.assign({}, row)
    },
    onOk () {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          this.$Message.success('Success!');

          let item = Object.assign({} , this.editForm.item)
          item.roles = item.roles.join(',')
          userApi.save(item).then(res => {
            this.editForm.visible = false
            this.list()
          })
        } else {
          this.$Message.error('Fail!');
        }
      })
    },
    onCancel () {
      this.$refs['form'].resetFields();
    },
    onDelete (params) {
      console.log('onDelete', params)
    },
    onSelectionChange (selection) {
      console.log('onSelectionChange', selection)
      this.selection = selection
    },
    onPageChange (current) {
      this.page.current = current
      this.list()
    },
    onPageSizeChange (pageSize) {
      this.page.pageSize = pageSize
      this.list()
    },
    onSortChange ({column, key, order}) {
      this.page.sort = {key, order}
      this.list()
    },
    list () {
      this.loading = true
      userApi.list(this.page).then(res => {
        this.loading = false
        let data = res.data.data
        for(let i in data.content){
          let item = data.content[i]
          item.roles = item.roles ? item.roles.split(',') : []
        }
        this.tableData = data.content
        this.page.total = data.totalElements
        this.selection = []
      })
    }
  },
  mounted () {
    this.list()
  }
}
</script>

<style>

</style>
